package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blog.config.PublisherAware;
import com.example.blog.domain.Picture;
import com.example.blog.domain.Response;
import com.example.blog.domain.UuId;
import com.example.blog.dto.operationalLogs.OperationLogsDto;
import com.example.blog.dto.picture.AddPictureDto;
import com.example.blog.dto.picture.DelPictureDto;
import com.example.blog.dto.picture.UpdatePictureDto;
import com.example.blog.event.publisher.LoggingApplicationEvent;
import com.example.blog.exception.BusinessException;
import com.example.blog.mapper.PictureMapper;
import com.example.blog.service.PictureService;
import com.example.blog.utils.UploadTheFile;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {


    private final UuIdServiceImpl uuIdService;
    private final PublisherAware publisherAware;
    private final PictureMapper pictureMapper;

    @Autowired
    PictureServiceImpl(UuIdServiceImpl uuIdService, PublisherAware publisherAware, PictureMapper pictureMapper) {
        this.uuIdService = uuIdService;
        this.publisherAware = publisherAware;
        this.pictureMapper = pictureMapper;
    }


    //新增精美图片
    @Override
    public String addPictureImg(MultipartFile[] file, AddPictureDto picture, OperationLogsDto logsDto) {
        String img = null;
        try {
            Picture picture_ = new Picture();
            picture_.setUid(logsDto.getAdmin().getUid());
            img = uploadImg(file);
            picture_.setType(picture.getType().replace('，', ','));
            picture_.setDescription(picture.getDescription());
            picture_.setPath(img);
            picture_.setStatue(1);
            int insert = pictureMapper.insert(picture_);
            if (img == null || insert<0) {
                throw new BusinessException(Response.ERROR_CODE, "上传失败");
            }
            logsDto.setOutcome(1);
            logsDto.setCustomer("图片id:".concat(String.valueOf(picture_.getId())));
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
        } catch (Exception e) {
            logsDto.setOutcome(0);
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
            throw e;
        }
        return img;
    }



    //更新精美图片
    @Override
    public String updatePictureImg(UpdatePictureDto pictureDto,OperationLogsDto logsDto) {
       try{
            Optional.ofNullable(pictureDto.getFile())
                    .ifPresent(s->{
                        String img = uploadImg(new MultipartFile[]{pictureDto.getFile()});
                        delImg(pictureDto.getPath()); //删除旧图片
                        pictureDto.setPath(img);
                    });
            UpdateWrapper<Picture> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", pictureDto.getId());
            Picture picture = new Picture();
            BeanUtils.copyProperties(pictureDto, picture);
            pictureMapper.update(picture,updateWrapper);
            logsDto.setOutcome(1);
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
        }catch (Exception e){
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
            throw e;
        }
       return null;
    }

    //删除精美图片
    @Override
    public Integer delPictureImg(DelPictureDto delPictureDto, OperationLogsDto logsDto) {
        logsDto.setOutcome(1);
        int delete = 0;
        try {
            delImg(delPictureDto.getPath());
            LambdaQueryWrapper<Picture> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Picture::getId, delPictureDto.getId());
            delete = pictureMapper.delete(wrapper);
            if (delete < 1) {
                throw new BusinessException(Response.ERROR_CODE, "删除失败");
            }
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
        } catch (Exception e) {
            logsDto.setOutcome(0);
            publisherAware.publisher(new LoggingApplicationEvent(logsDto));
            throw e;
        }
        return delete;
    }


    //删除图片
    public Integer delImg(String oldImg) {
        UploadTheFile uploadTheFile = new UploadTheFile();
        //检查传来的文件名是否有‘/’有，则进行截取‘/’后的字符，再进行删除
        String[] fileName = UploadTheFile.intercept(new String[]{oldImg}, "/");
        // 删除oss存储的图片返回删除成功数量
        Integer length = uploadTheFile.deleteFile(fileName);
        //删除数据库的uuid
        LambdaQueryWrapper<UuId> wrapper = new LambdaQueryWrapper<>();
        uuIdService.remove(wrapper.eq(UuId::getUuidValue, oldImg));
        return length;
    }


    //上传图片
    public String uploadImg(MultipartFile[] file) {
        UploadTheFile uploadTheFile = new UploadTheFile();
        //如果文件个数不是一个，并且文件类型不对，返回空
        if (UploadTheFile.fileFormat(file) || file.length != 1)
            return null;
        List<String> keys = uuIdService.randomUUid(file.length);
        //上传图片后，返回地址
        List<String> path = uploadTheFile.uploadFile(file, keys);
        //插入生成的uuid数据存储
        List<UuId> uuIds = new ArrayList<>();
        for (String s : path) {
            UuId uuId = new UuId();
            uuId.setUuidValue(s);
            uuIds.add(uuId);
        }
        uuIdService.saveBatch(uuIds);
        return path.get(0);
    }
}
